#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年9月8日

@author: chenyongbing
'''
import sys,os
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]

'''
    获取访问 门店 A 的顾客 同时也访问 其他门店 的 人数、停留时长

'''
import logging
sys.path.append(os.path.join(current_dir,'../'))
from base.retail_datas import myRetailDatas
from base.time_method import myTimeMethod

def get_sum_dur_from_roledata_by_macs(roledata,macs=[]):
    sum_dur = 0
    for mac,macdatas in roledata.items():
        if mac not in macs:continue
        for macdata in macdatas:
            dur = macdata['dur']
            sum_dur+=int(dur)
    return sum_dur
        

def getRoleFromHiveFile(day=None,groups = [],rawpath='/Udisk/new_role/',timeRange=None,roles=[1,-1,3,10],EMPLOYEES=[]):
    rfile = '%s/%s/part-00000'%(rawpath,day)
    #2015-08-01,32013138,d8:bb:2c:f0:60:73,2015-08-01 18:10:48,2015-08-01 18:10:48,0,1,Apple
    datas = {}
    if timeRange!=None and re.search('[\d]{2}:[\d]{2}:[\d]{2},[\d]{2}:[\d]{2}:[\d]{2}',timeRange):
        min_time,max_time = timeRange.split(',')
    elif timeRange == None:
        min_time = '00:00:00'
        max_time = '23:59:59'
    else:
        logging.error('timeRange %s fromat Error,use default min and max time.'%timeRange)
        min_time = '00:00:00'
        max_time = '23:59:59'
    
    if not os.path.exists(rfile):
        logging.error('role file %s not exists'%rfile)
        return datas
    for line in open(rfile).read().split('\n'):
        pass
        lineList = line.split(',')
        if len(lineList) < 8:continue
        group = lineList[1]
        if int(group) not in groups:continue
        mac = lineList[2]
        st = lineList[3][11:]
        et = lineList[4][11:]
        
        if st < min_time or st > max_time:
            logging.warn('st %s not in (%s,%s)'%(st,min_time,max_time))
            continue 
        if  mac in EMPLOYEES:
            logging.info('mac %s is employee.'%mac)
            continue
        dur = lineList[5]
        role = lineList[6]
        if int(role) not in roles and role not in roles:continue
        fac = lineList[7]
        if group not in datas.keys():
            datas[group] = {}
        if mac not in datas[group].keys():
            datas[group][mac] = []
            
        datas[group][mac].append({'st':st,'et':et,'dur':dur,'role':role,'fac':fac})
    return datas


def stat_cross_shop_flow(st=None,et=None,group=None,comp_id=None,timeRange='09:30:00,16:30:00',EMPLOYEES=[],roles=[1,-1,3,10]):
    if group == None or comp_id==None:
        logging.error('You Must Enter A Exists Shop Group.')
    group_name = myRetailDatas.get_group_name(group=group)
    print ','.join([u'日期',u'%s 到访人数'%group_name,u'交叉门店',u'交叉访问人数',u'交叉访问占比',u'停留总时长(秒)',u'停留平均时长(秒)'])
    groups = myRetailDatas.get_groups_by_comp(comp_id=comp_id)
    logging.info('groups %s'%len(group))
    days  = myTimeMethod.get_slist_between_st_et(st, et)
    for day in days:
        roledatas = getRoleFromHiveFile(day=day, groups=groups,timeRange = timeRange,roles=roles,EMPLOYEES=EMPLOYEES)
        logging.info('roledatas length %s'%len(roledatas))
        if group not in roledatas.keys():
            logging.error('Shop Group %s Not Found Any Role.'%group)
            continue
        cross_groupdatas = roledatas[group]
        cross_groupmacs = cross_groupdatas.keys()
        for shop_group , groupdatas in roledatas.iteritems():
            if shop_group == group:continue
            groupmacs = groupdatas.keys()
            shop_group_name = myRetailDatas.get_group_name(group=shop_group)
            #samemacs = list(set(cross_groupmacs) and set(groupmacs))
            samemacs = list(set(cross_groupmacs).intersection(set(groupmacs)))
            flow_num = len(samemacs)
            flow_sum_dur = get_sum_dur_from_roledata_by_macs(groupdatas,samemacs)/1000
            cross_flow_num = len(cross_groupmacs)
            #print day,shop_group,len(cross_groupmacs),flow_num,flow_sum_dur
            print ','.join([day,str(cross_flow_num),shop_group_name,str(flow_num),str(round(float(flow_num)/cross_flow_num,2)),str(flow_sum_dur),str(flow_sum_dur/flow_num)])
            
            
compEMPLOYEES = {'260':["0c:1d:af:de:b3:92","14:b9:68:11:5e:bc","34:e2:fd:23:5d:08","38:bc:1a:4a:ec:47","54:27:1e:67:45:d6","54:9f:13:1d:67:f6","58:66:ba:9e:4f:50","64:09:80:cf:df:72","64:9a:be:14:22:cd","64:a6:51:a4:c1:e0","9c:99:a0:a3:46:0d","a8:5b:78:22:35:3a","ac:f7:f3:c2:61:ba","b4:43:0d:70:37:85","b8:bc:1b:54:c7:e7","d4:f4:6f:49:6a:c7","fc:e9:98:36:1a:1b"],
                 '259':["bc:3a:ea:1e:3a:0e","00:ee:bd:06:ca:08","18:59:36:7a:3b:2f","18:59:36:ca:e2:33","48:5d:60:16:29:e2","ac:f7:f3:af:2b:1c","b0:65:bd:a1:50:0a","bc:3a:ea:1e:3a:0e","cc:29:f5:86:c6:17","cc:78:5f:74:eb:44","f8:a4:5f:37:e1:47"],
                 '262':["34:80:b3:3c:1b:b5","ac:f7:f3:af:2b:1c","f8:a4:5f:37:e1:47"]
                 }
        


if __name__ == '__main__':
    import argparse,re,datetime,time
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--st',metavar=u"starttime",default=None)
    parser.add_argument('--et',metavar="endTime",default=None)
    parser.add_argument('--group',metavar="group",default=None)
    parser.add_argument('--comp_id',metavar="cmp_id",default=None)
    parser.add_argument('--roles',metavar="roles",default="1,-1,3,10")
    args = parser.parse_args()
    st = args.st
    et = args.et
    group = args.group
    comp_id = args.comp_id
    roles = args.roles.split(',')
    #logging.basicConfig(level = logging.DEBUG)
    if comp_id in compEMPLOYEES.keys():
        EMPLOYEES = compEMPLOYEES[comp_id]
    else:
        EMPLOYEES = []
    stat_cross_shop_flow(st=st,et=et,group=group,comp_id=comp_id,EMPLOYEES=EMPLOYEES,roles=roles,timeRange=None)
    